/**
 * 
 */
package org.stars.util.reflect;

import java.lang.reflect.Method;

/**
 * @author Francesco Benincasa
 * 
 */
public abstract class StackTraceUtil {
	
	public final static Method getCurrentMethod(Object o) {
		return getCurrentMethod(o,0);
	}
	
	/**
	 * Inspect the stack trace of the current thread and take methods of the
	 * object used.
	 * 
	 * @param o
	 * @param offset
	 * @return
	 */
	public final static Method getCurrentMethod(Object o, int offset) {
		StackTraceElement current = null;
		StackTraceElement[] element = Thread.currentThread().getStackTrace();
		StackTraceElement item;

		// get the current methods
		String thisMethod = "getCurrentMethod";
		String stackMethod;

		for (int i = 0; i < element.length; i++) {
			item = element[i];
			stackMethod = item.getMethodName();

			if (stackMethod.equals(thisMethod)) {
				current = element[(++i) + offset];
				break;
			}
		}

		if (current == null)
			return null;
				

		String s = current.getMethodName();
		Method cm = null;
		for (Method m : o.getClass().getMethods()) {
			if (m.getName().equals(s)) {
				cm = m;
				break;
			}
		}
		return cm;
	}
}
